package com.yuexunit.operationman.nbsy.module.AfterOperation.ui;

import android.content.Context;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.bumptech.glide.Glide;

import com.yuexunit.operationman.nbsy.R;
import com.yuexunit.operationman.nbsy.base.BaseKJActivity;
import com.yuexunit.operationman.nbsy.base.SubmitBean;
import com.yuexunit.operationman.nbsy.config.AppConfig;
import com.yuexunit.operationman.nbsy.module.AfterOperation.bean.AfterOperationBean;
import com.yuexunit.operationman.nbsy.module.AfterOperation.model.impl.AfterOperationModel;
import com.yuexunit.operationman.nbsy.module.AfterOperation.presenter.IAfterOperationPresenter;
import com.yuexunit.operationman.nbsy.module.AfterOperation.presenter.impl.AfterOperationPresenter;
import com.yuexunit.operationman.nbsy.module.AfterOperation.ui.view.IAfterOperationView;
import com.yuexunit.operationman.nbsy.module.SafeOperation.bean.SignBean;
import com.yuexunit.operationman.nbsy.module.SafeOperation.model.impl.SafeOperationSignModel;
import com.yuexunit.operationman.nbsy.module.SafeOperation.presenter.ISafeOperationSignPresenter;
import com.yuexunit.operationman.nbsy.module.SafeOperation.presenter.impl.SafeOperationSignPresenter;
import com.yuexunit.operationman.nbsy.module.SafeOperation.ui.view.ISafeOperationSignView;
import com.yuexunit.operationman.nbsy.widget.ActionSheetDialog;
import com.yuexunit.operationman.nbsy.widget.ClickDialog;
import com.yuexunit.operationman.nbsy.widget.CustomDatePicker;
import com.yuexunit.operationman.nbsy.widget.LoadingDialog;
import com.yuexunit.operationman.nbsy.widget.LoginDialog;

import org.kymjs.kjframe.ui.ViewInject;
import org.kymjs.kjframe.utils.PreferenceHelper;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by chenss on 2017/8/10 0010.
 */

public class Act_AfterOperation_AnalgesiaObserveForm extends BaseKJActivity implements ISafeOperationSignView, IAfterOperationView {

    @Bind(R.id.tv_patient_name)
    TextView tvPatientName;
    @Bind(R.id.tv_patient_sex)
    TextView tvPatientSex;
    @Bind(R.id.tv_patient_visitno)
    TextView tvPatientVisitno;
    @Bind(R.id.tv_patient_disease)
    TextView tvPatientDisease;
    @Bind(R.id.select_time)
    TextView selectTime;
    @Bind(R.id.num_01)
    TextView num01;
    @Bind(R.id.num_02)
    TextView num02;
    @Bind(R.id.num_03)
    TextView num03;
    @Bind(R.id.radio_02_01)
    RadioButton radio0201;
    @Bind(R.id.radio_02_02)
    RadioButton radio0202;
    @Bind(R.id.radio_03_01)
    RadioButton radio0301;
    @Bind(R.id.radio_03_02)
    RadioButton radio0302;
    @Bind(R.id.radio_04_01)
    RadioButton radio0401;
    @Bind(R.id.radio_04_02)
    RadioButton radio0402;

    //签名
    @Bind(R.id.img_ao_sign_03)
    ImageView imgAoSign03;
    @Bind(R.id.btn_ao_sign_03)
    TextView btnAoSign03;
    @Bind(R.id.tv_ao_sign_03_time)
    TextView tvAoSign03Time;
    @Bind(R.id.tv_ao_sign_03_name)
    TextView tvAoSign03Name;
    @Bind(R.id.ao_sign_name)
    TextView aoSignName;

    int scale = 0;
    int scale2 = 0;
    int scale3 = 0;

    private CustomDatePicker customDatePicker1;
    private int type = -1;

    LoadingDialog loadingDialog;
    IAfterOperationPresenter presenter;

    AfterOperationBean.ObjectEntity.AoVisitPainListEntity aoVisitPainListEntity = new AfterOperationBean.ObjectEntity.AoVisitPainListEntity();

    LoginDialog loginDialog;
    ISafeOperationSignPresenter presenter_sign;

    ClickDialog dialog;

    @Override
    public void setRootView() {
        setContentView(R.layout.act_afteroperation_analgesiaobserveform);
        ButterKnife.bind(this);
    }

    @Override
    public void initData() {
        super.initData();
        type = getIntent().getExtras().getInt("type");
        loginDialog = new LoginDialog(aty);
        loadingDialog = new LoadingDialog(this);
        presenter = new AfterOperationPresenter(this, new AfterOperationModel());
        presenter_sign = new SafeOperationSignPresenter(this, new SafeOperationSignModel());
        setTitle();
        setContent();
    }

    private void setTitle() {
        tvPatientName.setText(AppConfig.AFTEROPERATIONBEAN.getObject().getAoVisit().getPatientName());
        if (AppConfig.AFTEROPERATIONBEAN.getObject().getAoVisit().getPatientSex().equals("1")) {
            tvPatientSex.setText("男");
        } else if (AppConfig.AFTEROPERATIONBEAN.getObject().getAoVisit().getPatientSex().equals("2")) {
            tvPatientSex.setText("女");
        } else {
            tvPatientSex.setText("不详");
        }
        tvPatientVisitno.setText("住院号" + AppConfig.AFTEROPERATIONBEAN.getObject().getAoVisit().getInHospitalNo());
        tvPatientDisease.setText(PreferenceHelper.readString(aty, AppConfig.PATIENT_INFO, AppConfig.PATIENT_DISEASE));
    }

    private void setContent() {
        switch (type) {
            case 1:
                aoVisitPainListEntity = AppConfig.AFTEROPERATIONBEAN.getObject().getAoVisitPainList().get(0);
                aoSignName.setText("观察医生（麻醉术后镇痛观察记录一）");
                if (AppConfig.AFTEROPERATIONBEAN.getObject().getAoVisitPainList().get(0).getObDoctorSignUrl() != null
                        && AppConfig.AFTEROPERATIONBEAN.getObject().getAoVisitPainList().get(0).getObDoctorSignUrl().length() > 0) {
                    imgAoSign03.setVisibility(View.VISIBLE);
                    btnAoSign03.setVisibility(View.GONE);
                    tvAoSign03Time.setVisibility(View.VISIBLE);
                    tvAoSign03Name.setVisibility(View.VISIBLE);
                    Glide.with(aty)
                            .load(AppConfig.AFTEROPERATIONBEAN.getObject().getAoVisitPainList().get(0).getObDoctorSignUrl())
                            .placeholder(R.color.white)
                            .error(R.color.white)
                            .into(imgAoSign03);
                    tvAoSign03Time.setText("签名时间:" + AppConfig.AFTEROPERATIONBEAN.getObject().getAoVisitPainList().get(0).getObDoctorSignTimeStr());
                    tvAoSign03Name.setText(AppConfig.AFTEROPERATIONBEAN.getObject().getAoVisitPainList().get(0).getObDoctorSign());
                }
                break;
            case 2:
                aoVisitPainListEntity = AppConfig.AFTEROPERATIONBEAN.getObject().getAoVisitPainList().get(1);
                aoSignName.setText("观察医生（麻醉术后镇痛观察记录二）");
                if (AppConfig.AFTEROPERATIONBEAN.getObject().getAoVisitPainList().get(1).getObDoctorSignUrl() != null
                        && AppConfig.AFTEROPERATIONBEAN.getObject().getAoVisitPainList().get(1).getObDoctorSignUrl().length() > 0) {
                    imgAoSign03.setVisibility(View.VISIBLE);
                    btnAoSign03.setVisibility(View.GONE);
                    tvAoSign03Time.setVisibility(View.VISIBLE);
                    tvAoSign03Name.setVisibility(View.VISIBLE);
                    Glide.with(aty)
                            .load(AppConfig.AFTEROPERATIONBEAN.getObject().getAoVisitPainList().get(1).getObDoctorSignUrl())
                            .placeholder(R.color.white)
                            .error(R.color.white)
                            .into(imgAoSign03);
                    tvAoSign03Time.setText("签名时间:" + AppConfig.AFTEROPERATIONBEAN.getObject().getAoVisitPainList().get(1).getObDoctorSignTimeStr());
                    tvAoSign03Name.setText(AppConfig.AFTEROPERATIONBEAN.getObject().getAoVisitPainList().get(1).getObDoctorSign());
                }
                break;
        }

        if (aoVisitPainListEntity.getAoVisitId() != null) {
            if (aoVisitPainListEntity.getObTimeStr() != null) {
                selectTime.setText(aoVisitPainListEntity.getObTimeStr());
            }

            if (aoVisitPainListEntity.getVasQuiet() != null) {
                num01.setText(aoVisitPainListEntity.getVasQuiet());
            }

            if (aoVisitPainListEntity.getVasAction() != null) {
                num02.setText(aoVisitPainListEntity.getVasAction());
            }

            if (aoVisitPainListEntity.getRamsayQuiet() != null) {
                num03.setText(aoVisitPainListEntity.getRamsayQuiet());
            }

            if (aoVisitPainListEntity.getSick() != null && aoVisitPainListEntity.getSick().length() > 0) {
                if (aoVisitPainListEntity.getSick().equals("1")) {
                    radio0201.setChecked(true);
                }
                if (aoVisitPainListEntity.getSick().equals("0")) {
                    radio0202.setChecked(true);
                }
            }

            if (aoVisitPainListEntity.getVomit() != null && aoVisitPainListEntity.getVomit().length() > 0) {
                if (aoVisitPainListEntity.getVomit().equals("1")) {
                    radio0301.setChecked(true);
                }
                if (aoVisitPainListEntity.getVomit().equals("0")) {
                    radio0302.setChecked(true);
                }
            }

            if (aoVisitPainListEntity.getPruritus() != null && aoVisitPainListEntity.getPruritus().length() > 0) {
                if (aoVisitPainListEntity.getPruritus().equals("1")) {
                    radio0401.setChecked(true);
                }
                if (aoVisitPainListEntity.getPruritus().equals("0")) {
                    radio0402.setChecked(true);
                }
            }
        }
    }

    @OnClick({R.id.titlebar_docadvice_img_back, R.id.iv_select_time,
            R.id.subtract_01, R.id.add_01, R.id.subtract_02, R.id.add_02,
            R.id.subtract_03, R.id.add_03, R.id.sure, R.id.btn_ao_sign_03})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.titlebar_docadvice_img_back:
                finish();
                break;
            case R.id.iv_select_time:
                initDatePicker(selectTime);
                break;
            case R.id.subtract_01:
                if (scale > 0) {
                    scale--;
                } else {
                    scale = 10;
                }
                num01.setText(scale + "");
                break;
            case R.id.add_01:
                if (scale < 10) {
                    scale++;
                } else {
                    scale = 0;
                }
                num01.setText(scale + "");
                break;
            case R.id.subtract_02:
                if (scale2 > 0) {
                    scale2--;
                } else {
                    scale2 = 10;
                }
                num02.setText(scale2 + "");
                break;
            case R.id.add_02:
                if (scale2 < 10) {
                    scale2++;
                } else {
                    scale2 = 0;
                }
                num02.setText(scale2 + "");
                break;
            case R.id.subtract_03:
                if (scale3 > 0) {
                    scale3--;
                } else {
                    scale3 = 10;
                }
                num03.setText(scale3 + "");
                break;
            case R.id.add_03:
                if (scale3 < 10) {
                    scale3++;
                } else {
                    scale3 = 0;
                }
                num03.setText(scale3 + "");
                break;
            case R.id.sure:
                switch (type)
                {
                    case 1:
                        if( AppConfig.AFTEROPERATIONBEAN.getObject().getAoVisitPainList().get(0).getObDoctorSign()!=null&&
                                AppConfig.AFTEROPERATIONBEAN.getObject().getAoVisitPainList().get(0).getObDoctorSign().length()>0) {
                            insertContent();
                        }
                        else {
                            dialog = new ClickDialog(aty).builder().setTxt("存在未签名,是否提交？");
                            dialog.isCancleBack(true);
                            dialog.setCallBack(new ClickDialog.ICallBack() {
                                @Override
                                public void callback(Bundle bundle) {
                                    if(bundle.getInt("data") == 0){
                                        insertContent();
                                    } else if(bundle.getInt("data") == 1){
                                        dialog.dismiss();
                                    }

                                }
                            });
                            dialog.show();
                        }
                        break;
                    case 2:
                        if( AppConfig.AFTEROPERATIONBEAN.getObject().getAoVisitPainList().get(1).getObDoctorSign()!=null&&
                                AppConfig.AFTEROPERATIONBEAN.getObject().getAoVisitPainList().get(1).getObDoctorSign().length()>0) {
                            insertContent();
                        }
                        else {
                            dialog = new ClickDialog(aty).builder().setTxt("存在未签名,是否提交？");
                            dialog.isCancleBack(true);
                            dialog.setCallBack(new ClickDialog.ICallBack() {
                                @Override
                                public void callback(Bundle bundle) {
                                    if(bundle.getInt("data") == 0){
                                        insertContent();
                                    } else if(bundle.getInt("data") == 1){
                                        dialog.dismiss();
                                    }

                                }
                            });
                            dialog.show();
                        }
                        break;
                }
                break;
            case R.id.btn_ao_sign_03:
                showTypeDialog();
                break;
        }
    }

    private void showTypeDialog() {
        ActionSheetDialog actionSheetDialog;
        actionSheetDialog = new ActionSheetDialog(this).builder()
                .setCancelable(true)
                .setCanceledOnTouchOutside(true);
        actionSheetDialog.addSheetItem("HIS签名", ActionSheetDialog.SheetItemColor.Blue,
                new ActionSheetDialog.OnSheetItemClickListener() {
                    @Override
                    public void onClick(int which) {
                        loginDialog.builder();
                        loginDialog.show();
                        loginDialog.setCallBack(new LoginDialog.ICallBack() {
                            @Override
                            public void callback(Bundle bundle) {
                                Map<String, String> params = new HashMap<>();
                                params.put("jobNum", bundle.getString("person_num"));
                                params.put("loginPwd", bundle.getString("person_psw"));
                                presenter_sign.getSignInfo(params);
                            }
                        });
                    }
                });
        actionSheetDialog.addSheetItem("虹膜签名(暂不可用)", ActionSheetDialog.SheetItemColor.Blue,
                new ActionSheetDialog.OnSheetItemClickListener() {
                    @Override
                    public void onClick(int which) {

                    }
                });
        actionSheetDialog.show();
    }

    @Override
    public void getSignInfo(SignBean signBean) {
        loginDialog.dismiss();
        if (signBean.getCode() == 200) {
            if (signBean.getObject().getDoctorType().equals("Y")) {
                SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", java.util.Locale.getDefault());
                Date curDate = new Date(System.currentTimeMillis());//获取当前时间
                String str = formatter.format(curDate);
                switch (type) {
                    case 1:
                        imgAoSign03.setVisibility(View.VISIBLE);
                        Glide.with(this)
                                .load(signBean.getObject().getSignPicture())
                                .placeholder(R.color.white)
                                .error(R.color.white)
                                .into(imgAoSign03);
                        btnAoSign03.setVisibility(View.GONE);
                        tvAoSign03Time.setVisibility(View.VISIBLE);
                        tvAoSign03Time.setText("签名时间:" + str);
                        tvAoSign03Name.setVisibility(View.VISIBLE);
                        tvAoSign03Name.setText(signBean.getObject().getDoctorName());

                        AppConfig.AFTEROPERATIONBEAN.getObject().getAoVisitPainList().get(0).setObDoctorSign(signBean.getObject().getDoctorName());
                        AppConfig.AFTEROPERATIONBEAN.getObject().getAoVisitPainList().get(0).setObDoctorSignUrl(signBean.getObject().getSignPicture());
                        AppConfig.AFTEROPERATIONBEAN.getObject().getAoVisitPainList().get(0).setObDoctorSignTimeStr(str);
                        break;
                    case 2:
                        imgAoSign03.setVisibility(View.VISIBLE);
                        Glide.with(this)
                                .load(signBean.getObject().getSignPicture())
                                .placeholder(R.color.white)
                                .error(R.color.white)
                                .into(imgAoSign03);
                        btnAoSign03.setVisibility(View.GONE);
                        tvAoSign03Time.setVisibility(View.VISIBLE);
                        tvAoSign03Time.setText("签名时间:" + str);
                        tvAoSign03Name.setVisibility(View.VISIBLE);
                        tvAoSign03Name.setText(signBean.getObject().getDoctorName());

                        AppConfig.AFTEROPERATIONBEAN.getObject().getAoVisitPainList().get(1).setObDoctorSign(signBean.getObject().getDoctorName());
                        AppConfig.AFTEROPERATIONBEAN.getObject().getAoVisitPainList().get(1).setObDoctorSignUrl(signBean.getObject().getSignPicture());
                        AppConfig.AFTEROPERATIONBEAN.getObject().getAoVisitPainList().get(1).setObDoctorSignTimeStr(str);
                        break;
                }
            } else {
                ViewInject.toast("请使用医生账号进行签名");
            }
        } else {
            ViewInject.toast(signBean.getDesc());
        }
    }

    private void insertContent() {
        if (selectTime.getText().length() > 0) {
            aoVisitPainListEntity.setObTimeStr(selectTime.getText().toString());
        }

        if (num01.getText().length() > 0) {
            aoVisitPainListEntity.setVasQuiet(num01.getText().toString());
        }

        if (num02.getText().length() > 0) {
            aoVisitPainListEntity.setVasAction(num02.getText().toString());
        }
        if (num03.getText().length() > 0) {
            aoVisitPainListEntity.setRamsayQuiet(num03.getText().toString());
        }

        if (radio0201.isChecked()) {
            aoVisitPainListEntity.setSick("1");
        }
        if (radio0202.isChecked()) {
            aoVisitPainListEntity.setSick("0");
        }

        if (radio0301.isChecked()) {
            aoVisitPainListEntity.setVomit("1");
        }
        if (radio0302.isChecked()) {
            aoVisitPainListEntity.setVomit("0");
        }

        if (radio0401.isChecked()) {
            aoVisitPainListEntity.setPruritus("1");
        }
        if (radio0402.isChecked()) {
            aoVisitPainListEntity.setPruritus("0");
        }

        switch (type) {
            case 1:
                AppConfig.AFTEROPERATIONBEAN.getObject().getAoVisitPainList().set(0, aoVisitPainListEntity);
                break;
            case 2:
                AppConfig.AFTEROPERATIONBEAN.getObject().getAoVisitPainList().set(1, aoVisitPainListEntity);
                break;
        }

        if (AppConfig.AFTEROPERATIONBEAN.getObject().getAoVisit().getAoVisitId() == null) {
            Map<String, String> params = new HashMap<>();
            params.put("operationNo", PreferenceHelper.readString(aty, AppConfig.PATIENT_INFO, AppConfig.PATIENT_OPERATION_ID) + "");
            params.put("saveData", JSON.toJSONString(AppConfig.AFTEROPERATIONBEAN));
            presenter.insertAfterOperationDate(params);
        } else {
            Map<String, String> params = new HashMap<>();
            params.put("accountId", PreferenceHelper.readInt(aty, AppConfig.USER_INFO, AppConfig.USER_ACCOUNT) + "");
            params.put("fullName", PreferenceHelper.readString(aty, AppConfig.USER_INFO, AppConfig.USER_FULLNAME) + "");
            params.put("saveData", JSON.toJSONString(AppConfig.AFTEROPERATIONBEAN));
            presenter.updateAfterOperationDate(params);
        }
    }


    private void initDatePicker(final TextView view) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.CHINA);
        Date date1 = null;
        try {
            if (view.getText().toString().length() > 0) {
                date1 = sdf.parse(view.getText().toString());
            } else {
                date1 = new Date();
            }
        } catch (ParseException e) {
            e.printStackTrace();
        }
        String now = sdf.format(date1);

        CustomDatePicker customDatePicker1 = new CustomDatePicker(this, new CustomDatePicker.ResultHandler() {
            @Override
            public void handle(String time) { // 回调接口，获得选中的时间
                view.setText(time);
            }
        }, "2010-01-01 00:00", now); // 初始化日期格式请用：yyyy-MM-dd HH:mm，否则不能正常运行
        customDatePicker1.showSpecificTime(true); // 显示时和分
        customDatePicker1.setIsLoop(true); // 循环滚动
        customDatePicker1.show(now);
    }

    @Override
    public void insertAfterOperationDate(SubmitBean submitBean) {
        if (submitBean.getCode() == 200) {
            ViewInject.toast("保存成功");
            finish();
        } else {
            ViewInject.toast(submitBean.getDesc());
        }
    }

    @Override
    public void updateAfterOperationDate(SubmitBean submitBean) {
        if (submitBean.getCode() == 200) {
            ViewInject.toast("保存成功");
            finish();
        } else {
            ViewInject.toast(submitBean.getDesc());
        }
    }

    @Override
    public void loadingDialogStatus(int status) {
        switch (status) {
            case AppConfig.SHOW_DIALOG:
                loadingDialog.setCanceledOnTouchOutside(false);
                loadingDialog.show();
                break;
            case AppConfig.DISMISS_DIALOG:
                loadingDialog.dismiss();
                break;

        }
    }

    /**
     * 通过dispatchTouchEvent每次ACTION_DOWN事件中动态判断非EditText本身区域的点击事件，然后在事件中进行屏蔽。然后当点击不是EditText时候，进行隐藏键盘操作
     *
     * @param ev
     * @return
     */

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        if (ev.getAction() == MotionEvent.ACTION_DOWN) {
            View v = getCurrentFocus();
            if (isShouldHideInput(v, ev)) {

                InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                if (imm != null) {
                    imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
                }
            }
            return super.dispatchTouchEvent(ev);
        }
        if (getWindow().superDispatchTouchEvent(ev)) {
            return true;
        }
        return onTouchEvent(ev);
    }

    public boolean isShouldHideInput(View v, MotionEvent event) {

        if (v != null && (v instanceof EditText)) {
            int[] leftTop = {0, 0};
            //获取输入框当前的location位置
            v.getLocationInWindow(leftTop);
            int left = leftTop[0];
            int top = leftTop[1];
            int bottom = top + v.getHeight();
            int right = left + v.getWidth();
            if (event.getX() > left && event.getX() < right
                    && event.getY() > top && event.getY() < bottom) {
                // 点击的是输入框区域，保留点击EditText的事件\
                return false;
            } else {
                return true;
            }
        }
        return false;
    }
}
